package com.sttk.secreconeclick.bookkeep.dialog;

import android.content.Context;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.lzb.basic.dialog.BaseSmartDialog;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.bean.PlanBean;
import com.sttk.secreconeclick.bookkeep.bean.SaveRecordBean;
import com.sttk.secreconeclick.bookkeep.databinding.DialogSaveMoneyBinding;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class SaveMoneyDialog extends BaseSmartDialog<DialogSaveMoneyBinding> implements View.OnClickListener {

    private int selPosition;
    private List<PlanBean> listSave;
    private PlanBean planBean;
    private SaveRecordBean recordBean;
    private SelDateDialog selDateDialog;

    // 图片选择相关变量
    private String selectedImagePath = "";

    // 计算器相关变量
    private StringBuilder currentExpression = new StringBuilder("");
    private StringBuilder currentInput = new StringBuilder("");
    private double currentValue = 0;
    private String lastOperator = "";
    private boolean isNewInput = true;
    private boolean isSaveMode = false;
    private String currentDate = "";

    public SaveMoneyDialog(@NonNull Context context) {
        super(context);
    }

    public void setSelPosition(int selPosition) {
        this.selPosition = selPosition;
    }

    public void setSaveMode(boolean saveMode) {
        isSaveMode = saveMode;
    }

    @Override
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_save_money;
    }

    @Override
    protected void initView(View view) {
        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.ivImg.setOnClickListener(this);
        // 数字按钮
        mDataBinding.num0.setOnClickListener(this);
        mDataBinding.num1.setOnClickListener(this);
        mDataBinding.num2.setOnClickListener(this);
        mDataBinding.num3.setOnClickListener(this);
        mDataBinding.num4.setOnClickListener(this);
        mDataBinding.num5.setOnClickListener(this);
        mDataBinding.num6.setOnClickListener(this);
        mDataBinding.num7.setOnClickListener(this);
        mDataBinding.num8.setOnClickListener(this);
        mDataBinding.num9.setOnClickListener(this);
        mDataBinding.numDot.setOnClickListener(this);

        // 运算符按钮
        mDataBinding.btnAdd.setOnClickListener(this);
        mDataBinding.btnMinus.setOnClickListener(this);
        mDataBinding.btnDelete.setOnClickListener(this);

        // 功能按钮
        mDataBinding.btnRemember.setOnClickListener(this);
        mDataBinding.numEqual.setOnClickListener(this);

        listSave = AppSpUtils.getPlanList();
        planBean = listSave.get(selPosition);
        recordBean = new SaveRecordBean();

        // 初始化日期显示
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        currentDate = sdf.format(new Date());
        mDataBinding.tvDate.setText(currentDate);

        mDataBinding.tvMoney.setText("0");
        currentExpression.setLength(0);
        currentInput.setLength(0);
        currentValue = 0;
        lastOperator = "";
        isNewInput = true;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvDate) {//日期
            showSelDateDialog();
        } else if (id == R.id.ivImg) {//图片
            if (listener != null) {
                listener.clickOpenImg();
            }
        } else if (id == R.id.num_0 || id == R.id.num_1 || id == R.id.num_2 || id == R.id.num_3 ||
                id == R.id.num_4 || id == R.id.num_5 || id == R.id.num_6 || id == R.id.num_7 ||
                id == R.id.num_8 || id == R.id.num_9) {
            appendNumber(((TextView) v).getText().toString());
        } else if (id == R.id.num_dot) {
            appendDot();
        } else if (id == R.id.btn_add) {
            performOperation("+");
        } else if (id == R.id.btn_minus) {
            performOperation("-");
        } else if (id == R.id.btn_delete) {
            deleteLastDigit();
        } else if (id == R.id.btn_remember) {//再记
            rememberAgain();
        } else if (id == R.id.num_equal) {//完成
            completeCalculation();
        }
    }

    private void appendNumber(String number) {
        // 如果存在初始金额且尚未开始新输入，则清空并重置
        if (isNewInput) {
            currentInput.setLength(0);
            isNewInput = false;
        }

        // 如果当前是"0"且输入的不是小数点，替换0
        if (currentInput.length() == 1 && currentInput.toString().equals("0") && !number.equals(".")) {
            currentInput.setLength(0);
        }

        // 防止输入多个前导零
        if (currentInput.length() == 0 && number.equals("0")) {
            currentInput.append("0");
            updateExpressionDisplay();
            return;
        }

        // 检查小数位数限制（最多两位小数）
        if (currentInput.toString().contains(".")) {
            String[] parts = currentInput.toString().split("\\.");
            if (parts.length == 2 && parts[1].length() >= 2) {
                // 小数部分已经有两位，不再允许输入
                return;
            }
        }

        currentInput.append(number);

        // 更新表达式显示
        updateExpressionDisplay();
    }

    private void appendDot() {
        if (isNewInput) {
            currentInput.setLength(0);
            currentInput.append("0");
            isNewInput = false;
        } else if (currentInput.length() == 0) {
            currentInput.append("0");
        }

        // 防止输入多个小数点
        if (currentInput.toString().contains(".")) {
            return;
        }

        currentInput.append(".");

        // 更新表达式显示
        updateExpressionDisplay();
    }

    private void performOperation(String operator) {
        // 只在拼接表达式，不进行计算
        if (currentInput.length() > 0) {
            // 构建完整表达式
            if (currentExpression.length() == 0) {
                // 第一个数字
                currentExpression.append(currentInput.toString());
            } else if (!lastOperator.isEmpty()) {
                // 继续添加运算符和数字
                currentExpression.append(lastOperator).append(currentInput.toString());
            }

            lastOperator = operator;
            isNewInput = true;
            currentInput.setLength(0); // 清空当前输入

            // 显示当前状态（表达式 + 新的运算符）
            mDataBinding.tvMoney.setText(currentExpression.toString() + lastOperator);
        } else if (currentExpression.length() == 0 && lastOperator.isEmpty() && currentInput.length() == 0) {
            // 如果没有输入但有初始金额，将初始金额作为第一个操作数
            String initialAmount = mDataBinding.tvMoney.getText().toString();
            if (!initialAmount.equals("0")) {
                currentExpression.append(initialAmount);
                lastOperator = operator;
                isNewInput = true;
                currentInput.setLength(0);
                mDataBinding.tvMoney.setText(currentExpression.toString() + lastOperator);
            }
        }
    }

    private void calculateFinalResult() {
        // 构建完整的表达式
        StringBuilder fullExpression = new StringBuilder();

        if (currentExpression.length() > 0) {
            fullExpression.append(currentExpression.toString());
        }
        if (!lastOperator.isEmpty()) {
            fullExpression.append(lastOperator);
        }
        if (currentInput.length() > 0) {
            fullExpression.append(currentInput.toString());
        }

        String expr = fullExpression.toString();

        if (expr.isEmpty()) {
            return;
        }

        // 计算最终结果
        double result = evaluateExpression(expr);

        // 格式化结果保留两位小数
        String formattedResult = String.format("%.2f", result);

        // 重置计算器状态
        currentExpression.setLength(0);
        currentInput.setLength(0);
        currentInput.append(formattedResult);
        currentValue = result;
        lastOperator = "";
        isNewInput = true;

        // 显示最终结果
        updateMoneyDisplay();
    }

    private double evaluateExpression(String expression) {
        try {
            // 解析无空格的表达式，如"100+50-30"
            if (expression.isEmpty()) return 0;

            // 找到第一个运算符
            int firstOpIndex = -1;
            String firstOp = "";

            for (int i = 0; i < expression.length(); i++) {
                char c = expression.charAt(i);
                if (c == '+' || c == '-' || c == '×' || c == '÷') {
                    firstOpIndex = i;
                    firstOp = String.valueOf(c);
                    break;
                }
            }

            if (firstOpIndex == -1) {
                // 没有运算符，直接返回数字
                return Double.parseDouble(expression);
            }

            // 解析第一个数字
            double result = Double.parseDouble(expression.substring(0, firstOpIndex));

            // 继续解析剩余部分
            String remaining = expression.substring(firstOpIndex + 1);

            while (!remaining.isEmpty()) {
                // 找到下一个运算符
                int nextOpIndex = -1;
                String nextOp = "";

                for (int i = 0; i < remaining.length(); i++) {
                    char c = remaining.charAt(i);
                    if (c == '+' || c == '-' || c == '×' || c == '÷') {
                        nextOpIndex = i;
                        nextOp = String.valueOf(c);
                        break;
                    }
                }

                if (nextOpIndex == -1) {
                    // 没有更多运算符，处理最后一个数字
                    double operand = Double.parseDouble(remaining);

                    switch (firstOp) {
                        case "+":
                            result += operand;
                            break;
                        case "-":
                            result -= operand;
                            break;
                        case "×":
                            result *= operand;
                            break;
                        case "÷":
                            if (operand != 0) {
                                result /= operand;
                            }
                            break;
                    }
                    break;
                } else {
                    // 处理当前数字和运算符
                    double operand = Double.parseDouble(remaining.substring(0, nextOpIndex));

                    switch (firstOp) {
                        case "+":
                            result += operand;
                            break;
                        case "-":
                            result -= operand;
                            break;
                        case "×":
                            result *= operand;
                            break;
                        case "÷":
                            if (operand != 0) {
                                result /= operand;
                            }
                            break;
                    }

                    // 准备下一轮循环
                    firstOp = nextOp;
                    remaining = remaining.substring(nextOpIndex + 1);
                }
            }

            return result;
        } catch (Exception e) {
            return 0;
        }
    }

    private void deleteLastDigit() {
        // 构建完整的显示字符串
        StringBuilder fullDisplay = new StringBuilder();

        if (currentExpression.length() > 0) {
            fullDisplay.append(currentExpression.toString());
        }
        if (!lastOperator.isEmpty()) {
            fullDisplay.append(lastOperator);
        }
        if (currentInput.length() > 0) {
            fullDisplay.append(currentInput.toString());
        }

        String display = fullDisplay.toString();

        if (display.length() > 0) {
            // 删除最后一个字符
            display = display.substring(0, display.length() - 1);

            // 重新解析字符串
            parseDisplayString(display);
        }

        // 更新显示
        updateExpressionDisplay();
    }

    private void parseDisplayString(String display) {
        // 清空当前状态
        currentExpression.setLength(0);
        lastOperator = "";
        currentInput.setLength(0);

        if (display.isEmpty()) {
            return;
        }

        // 从后往前找最后一个运算符
        int lastOpIndex = -1;
        char lastOpChar = 0;

        for (int i = display.length() - 1; i >= 0; i--) {
            char c = display.charAt(i);
            if (c == '+' || c == '-' || c == '×' || c == '÷') {
                lastOpIndex = i;
                lastOpChar = c;
                break;
            }
        }

        if (lastOpIndex != -1) {
            // 有运算符
            lastOperator = String.valueOf(lastOpChar);

            // 运算符后的部分是currentInput
            if (lastOpIndex + 1 < display.length()) {
                currentInput.append(display.substring(lastOpIndex + 1));
            }

            // 运算符前的部分是currentExpression
            if (lastOpIndex > 0) {
                currentExpression.append(display.substring(0, lastOpIndex));
            }
        } else {
            // 没有运算符，整个都是currentInput
            currentInput.append(display);
        }
    }

    private void updateMoneyDisplay() {
        String displayText = currentInput.length() > 0 ? currentInput.toString() : "0";

        // 如果是数字，格式化为两位小数
        try {
            // 检查是否是小数点结尾的临时状态
            if (displayText.endsWith(".")) {
                // 小数点结尾，直接显示
                mDataBinding.tvMoney.setText(displayText);
                return;
            }
            
            double value = Double.parseDouble(displayText);
            displayText = String.format("%.2f", value);
            // 移除末尾的0和小数点
            displayText = displayText.replaceAll("0*$", "").replaceAll("\\.$", "");
        } catch (NumberFormatException e) {
            // 如果不是有效的数字，保持原样
        }

        mDataBinding.tvMoney.setText(displayText);
    }

    private void updateExpressionDisplay() {
        if (currentExpression.length() > 0 || !lastOperator.isEmpty()) {
            // 如果有表达式或运算符，显示组合内容
            StringBuilder display = new StringBuilder();

            if (currentExpression.length() > 0) {
                display.append(currentExpression.toString());
            }
            if (!lastOperator.isEmpty()) {
                display.append(lastOperator);
            }
            if (currentInput.length() > 0) {
                display.append(currentInput.toString());
            }

            mDataBinding.tvMoney.setText(display.toString());
        } else {
            // 没有表达式和运算符，只显示当前输入
            if (currentInput.length() > 0) {
                String displayText = currentInput.toString();
                // 格式化当前输入，保留两位小数
                try {
                    // 检查是否是小数点结尾的临时状态
                    if (displayText.endsWith(".")) {
                        // 小数点结尾，直接显示
                        mDataBinding.tvMoney.setText(displayText);
                    } else {
                        double value = Double.parseDouble(displayText);
                        displayText = String.format("%.2f", value);
                        // 移除末尾的0和小数点
                        displayText = displayText.replaceAll("0*$", "").replaceAll("\\.$", "");
                        mDataBinding.tvMoney.setText(displayText);
                    }
                } catch (NumberFormatException e) {
                    // 如果不是有效的数字，保持原样显示
                    mDataBinding.tvMoney.setText(displayText);
                }
            } else {
                mDataBinding.tvMoney.setText("0");
            }
        }
    }

    private void rememberAgain() {
        // 再记功能：先计算最终结果，再保存账单并重置计算器
        if (saveMoney()) {
            if (listener != null) {
                listener.clickConfirm();
            }
            resetCalculator();
        }
    }

    private void completeCalculation() {
        // 完成功能：先计算最终结果，再保存账单
        // 如果没有当前输入但有初始金额，使用初始金额
        if (currentInput.length() == 0 && currentExpression.length() == 0 && lastOperator.isEmpty()) {
            String initialAmount = mDataBinding.tvMoney.getText().toString();
            if (!initialAmount.equals("0")) {
                currentInput.append(initialAmount);
            }
        }
        if (saveMoney()) {
            dismiss();
            if (listener != null) {
                listener.clickConfirm();
            }
        }
    }

    private boolean saveMoney() {

        calculateFinalResult();

        // 确保有有效的金额
        if (currentInput.length() == 0) {
            ToastUtils.showShort(getContext().getString(R.string.please_input_money));
            return false;
        }

        double money = Double.parseDouble(currentInput.toString());

        // 判断结果是否小于0
        if (money <= 0) {
            ToastUtils.showShort(getContext().getString(R.string.money_no_zero));
            return false;
        }

        // 格式化金额保留两位小数
        money = Math.round(money * 100.0) / 100.0;

        String remark = mDataBinding.etRemark.getText().toString().trim();

        long date = TimeUtils.string2Millis(mDataBinding.tvDate.getText().toString(), new SimpleDateFormat("yyyy年MM月dd日"));

        recordBean.setDate(date);
        recordBean.setRemark(remark);
        recordBean.setMoney(money);
        recordBean.setSave(isSaveMode);
        recordBean.setImg(selectedImagePath);


        // 添加到当前账本的账单列表
        if (planBean.getRecordBeanList() == null) {
            planBean.setRecordBeanList(new ArrayList<>());
        }

        planBean.getRecordBeanList().add(recordBean);

        // 保存更新后的账本列表
        AppSpUtils.savePlanList(listSave);

        return true;
    }

    private void resetCalculator() {
        recordBean = new SaveRecordBean();
        currentInput.setLength(0);
        currentExpression.setLength(0);
        currentValue = 0;
        lastOperator = "";
        isNewInput = true;
        selectedImagePath = ""; // 重置图片路径
        mDataBinding.etRemark.setText("");
        updateMoneyDisplay();
    }

    private void showSelDateDialog() {
        if (selDateDialog == null) selDateDialog = new SelDateDialog(getContext());
        selDateDialog.setListener(new SelDateDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                mDataBinding.tvDate.setText(TimeUtils.millis2String(date, new SimpleDateFormat("yyyy年MM月dd日")));
            }
        });
        selDateDialog.show();
    }

    public void setImg(Uri selectedImageUri) {
        // 加载图片到ImageView
        Glide.with(getContext()).load(selectedImageUri).into(mDataBinding.ivImg);
        // 保存图片路径
        selectedImagePath = selectedImageUri.toString();
        if (recordBean != null) {
            recordBean.setImg(selectedImagePath);
        }
    }


    private Ilistener listener;

    public void setListener(Ilistener listener) {
        this.listener = listener;
    }

    public interface Ilistener {
        void clickConfirm();

        void clickOpenImg();
    }
}
